<?php

class SiteController extends Controller
{
	public $layout = '//layouts/pageBlock';
	
	public function actionIndex()
	{
		if(!Yii::app()->user->isGuest){
			$this->redirect($this->createUrl('site/home'));
		}
		$this->layout = '//layouts/pageClean';
		$this->render('index');
	}

	public function actionHome()
	{
		$this->render('home');
	}
	
	public function actionLogin()
	{
		$username = '';
		if(isset($_POST['Login'])){
			$username = $_POST['Login']['user_account'];
			$password = md5($_POST['Login']['user_password']);
			
			if($this->login($username, $password)){
				$this->redirect($this->createUrl('site/home'));
			}
		}
		$this->render('login',array('username'=>$username));
	}
	
	public function actionLogout()
	{
		Yii::app()->user->logout(); // คำสั่ง logout
		$this->redirect($this->createUrl('site/index')); // คำสั่งเปลี่ยนหน้า
	}
	
	public function actionSignup()
	{
		$user = new User;
		
		if(isset($_POST['Signup'])){
			$user->attributes = $_POST['Signup'];
			$user->user_password = md5($user->user_password);
			$user->room_id = 1;
			if($user->save() && $this->login($user->user_account, $user->user_password)){
				$this->redirect($this->createUrl('site/home'));
			}
			else
			{
				print_r($user->errors);
			}
		}
		$this->render('signup',array('user'=>$user));
	}
	
	public function login($username, $password)
	{
		$identity = new UserIdentity($username, $password);
		if($identity->authenticate()){
			Yii::app()->user->login($identity);
			return true;
		}
		return false;
	}
	
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}